package cc.rengu.redp.bizimpl.igas.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelCfg;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelInfo;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelCfgService;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysSeqService;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-09
 */
@Api(tags = "产品管理:支付通道配置管理")
@Slf4j
@RestController
@RequestMapping("/admin/igas/pDstChannelCfg")
public class PDstChannelCfgController extends BaseController {
    @Autowired
    private PDstChannelCfgService pDstChannelCfgService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;

    @GetMapping(value ="")
//    @RequiresPermissions("areaInfo:view")
    public Map<String, Object> list(QueryRequest request, PDstChannelCfg entity) {
        return getDataTable(this.pDstChannelCfgService.findByPage(request, entity));
    }

    @GetMapping(value = "/editFromChnl")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> editFromChnl( PDstChannelInfo pDstChannelInfo) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(pDstChannelInfo.getOptFlag())) {
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        }else if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(pDstChannelInfo.getOptFlag())
                ||PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(pDstChannelInfo.getOptFlag())){
            if(Common.isNotBlank(pDstChannelInfo.getSecPlanId())
                    &&pDstChannelInfo.getSecPlanId().startsWith(pDstChannelInfo.getDstChannelId())){//secPlanId中的DstChannelId未变时，secPlanId不变
            }else{
                pDstChannelInfo.setSecPlanId(genSecPlanId(pDstChannelInfo.getDstChannelId()));
            }
            pDstChannelInfoService.update(pDstChannelInfo);
        }
        PDstChannelCfg cfg = null;
        if(!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(pDstChannelInfo.getOptFlag())) {
            LambdaQueryWrapper<PDstChannelCfg> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PDstChannelCfg::getInstId, pDstChannelInfo.getInstId());
            wrapper.eq(PDstChannelCfg::getDstChannelId, pDstChannelInfo.getDstChannelId());
            wrapper.eq(PDstChannelCfg::getDstChannelType, pDstChannelInfo.getDstChannelType());
            cfg = pDstChannelCfgService.getOne(wrapper);
        }
        if(Common.isBlank(cfg)){
            cfg=new PDstChannelCfg();
            cfg.setInstId(pDstChannelInfo.getInstId());
            cfg.setDstChannelId(pDstChannelInfo.getDstChannelId());
            cfg.setSecPlanId(pDstChannelInfo.getSecPlanId());
            cfg.setOptFlag(pDstChannelInfo.getOptFlag());
            cfg.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        }
        cfg.setDstChannelName(pDstChannelInfo.getDstChannelId()+"("+pDstChannelInfo.getDstChannelName()+")");
        result.put("entity",cfg);
        result.put("pDstChannelInfo",pDstChannelInfo);
        result.put("optFlag",pDstChannelInfo.getOptFlag());
        return result;
    }


    @Log("修改")
    @PutMapping("/update")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelName", value = "通道名称", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public void update(@Valid PDstChannelCfg entity) throws RedpException {
        try {
            this.pDstChannelCfgService.update(entity);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }


    @GetMapping(value = "/select2List")
    @ApiImplicitParam(paramType = "query", name = "q", value = "机构标识|通道类型", dataType = "String")
    public List<Map<String, String>> select2List(String q) throws RedpException {
        try {
            return this.pDstChannelCfgService.select2List(q);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }
    /**
     * 安全计划编号，格式为: dstChannelId+8位排序编码
     * @return
     */
    private String genSecPlanId(String dstChannelId) {
        // 固定入参
        String common = "SEC_PLAN_ID";
        String prefix = dstChannelId;

//		dstChannelId+8位排序编码
        // 生成序列号
        String serialNumber = upmpSysSeqService.updateParamValue(common, prefix, "20");
        String result = prefix + String.format("%08d", Integer.parseInt(serialNumber));
        return  result;
    }
}
